package com.ymttest.business.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.json.JSONObject;

import com.ymatou.iapi.livemanage.service.CloseActivityCall;
import com.ymatou.iapi.livemanage.service.ConfirmActivityCall;
import com.ymatou.iapi.livemanage.service.CreateLiveCall;
import com.ymatou.iapi.livemanage.service.DelayActivityCall;
import com.ymatou.iapi.livemanage.service.SaveActivityCall;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.AppCountry;
import com.ymttest.database.model.YmtLive;
import com.ymttest.database.mongo.LiveBasicInfoWapper;
import com.ymttest.database.mongo.LiveModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.LivesWapper;
import com.ymttest.database.sqlwapper.AppCountryWapper;
import com.ymttest.database.sqlwapper.YmtLiveWapper;
import com.ymttest.database.sqlwapper.YmtProductActivityStockWapper;
import com.ymttest.database.sqlwapper.YmtProductBrandWapper;
import com.ymttest.database.sqlwapper.YmtProductCategoryWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.database.sqlwapper.YmtProductsInLiveWapper;
import com.ymttest.database.sqlwapper.YmtUsersWapper;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.JsonBeanFile;

public class LiveCallService {
	public static SimpleDateFormat liveSDF = YMTDateUtil.getYMDHMSFormat();
	public static YmtLiveWapper ymtLiveWapper = new YmtLiveWapper();
	public static LiveBasicInfoWapper liveBasicInfoWapper = new LiveBasicInfoWapper();
	public static LiveModelWapper liveModelWapper = new LiveModelWapper();
	public static LivesWapper livesWapper = new LivesWapper();

	/***
	 * 直播编辑保存
	 * 
	 * @param sellerName
	 * @param userId
	 * @param activityId
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject saveLive(String sellerName, int userId, int activityId, Map<String, Object> updateMap)
			throws Exception {
		JSONObject saveLiveBean = JsonBeanHelper.getJsonBean(JsonBeanFile.SaveActivityTpl);
		JsonBeanHelper.updateJsonBean(saveLiveBean, "Activity->ActivityId", activityId);
		JsonBeanHelper.updateJsonBean(saveLiveBean, "Activity->UserId", userId);
		JsonBeanHelper.updateJsonBean(saveLiveBean, "Activity->SellerName", userId);
		JsonBeanHelper.updateJsonBean(saveLiveBean, updateMap);

		SaveActivityCall saveActivityCall = new SaveActivityCall();
		saveActivityCall.setData(saveLiveBean);
		saveActivityCall.callService();
		return new JSONObject(saveActivityCall.getReturnData());

	}

	public static List<String> getProductsInLive(int liveId) throws InterruptedException {
		List<String> productIds = new ArrayList<String>();
		YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
		ymtProductsInLiveWapper.selectByLiveId(liveId).forEach(ele -> 
		{
			if (ele.getiAction()>-1){
				productIds.add(ele.getSproductid());
			}
		});
		return productIds;
	}

	public static List<Integer> getLivesWithProduct(String productId) throws InterruptedException {
		List<Integer> lives = new ArrayList<Integer>();
		YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
		ymtProductsInLiveWapper.selectInLiveByProductId(productId).forEach(ele -> {
			if (Integer.parseInt(ele.get("iAction").toString())>-1){
				lives.add(Integer.parseInt(ele.get("iActivityId").toString()));
			}
		});

		return lives;
	}
	
	
	
	
	public static List<Integer> getProdInActIdsWithProduct(String productId) throws InterruptedException{
		YmtProductActivityStockWapper ymtProductActivityStockWapper = new YmtProductActivityStockWapper();
		return ymtProductActivityStockWapper.selectByProductId(productId).stream()
					.filter(y->(y.getDendtime().after(YMTDateUtil.getDateBeforeOrNextSecond(-30))))
					.map(x->x.getIproductinactivityid()).distinct().collect(Collectors.toList());
	}

	/***
	 * 根据userid 获取username
	 * 
	 * @param userId
	 * @return
	 */
	public static String getLoginUserName(int userId) {
		YmtUsersWapper ymtUsersWapper = new YmtUsersWapper();
		return ymtUsersWapper.getLoginId(userId);
	}

	/***
	 * 获取英文名
	 * @param liveId
	 * @return
	 * @throws InterruptedException
	 */
	public static List<String> getProdBrandsInLive(int liveId) throws InterruptedException {
		List<String> brandList = new ArrayList<String>();
		List<String> productIds = new ArrayList<String>();

		YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
		ymtProductsInLiveWapper.selectByLiveId(liveId).forEach(ele -> {
			if (ele.getiAction()>-1){
				productIds.add(ele.getSproductid());
			}
		});

		YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
		for (String pid : productIds) {
			ymtProductsIWapper.selectProductByProductId(pid).forEach(ele -> brandList.add(ele.getsBrand()));
		}
		return brandList;
	}

	
	/***
	 * 获取中文名
	 * @param liveId
	 * @return
	 * @throws InterruptedException
	 */
	public static List<String> getProdSBrandsInLive(int liveId) throws InterruptedException{
		List<String> brandList = new ArrayList<String>();
		List<String> productIds = new ArrayList<String>();

		YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
		ymtProductsInLiveWapper.selectByLiveId(liveId).forEach(ele -> {
			if (ele.getiAction()>-1){
				productIds.add(ele.getSproductid());
			}
			
		});
		
		YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
		for (String pid : productIds) {
			ymtProductsIWapper.selectProductByProductId(pid).forEach(ele -> {
				if (!brandList.contains(ele.getsBrand())){
					brandList.add(ele.getsBrand());
				}
				
			});
		}
		return brandList;
		
	}
	
	
	/***
	 * 延迟直播
	 * 
	 * @param userId
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject delayLive(int userId, int activityId, Map<String, Object> updateMap) throws Exception {
		JSONObject delayLiveBean = JsonBeanHelper.getJsonBean(JsonBeanFile.DelayActivityTpl);

		JsonBeanHelper.updateJsonBean(delayLiveBean, "ActivityId", activityId);
		JsonBeanHelper.updateJsonBean(delayLiveBean, "UserId", userId);
		JsonBeanHelper.updateJsonBean(delayLiveBean, updateMap);

		DelayActivityCall delayActivityCall = new DelayActivityCall();
		delayActivityCall.setData(delayLiveBean);
		delayActivityCall.callService();

		return new JSONObject(delayActivityCall.getReturnData());

	}

	/***
	 * 创建6天后开始的直播
	 * 
	 * @param sellerName
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLiveBegin6dayInFuture(String sellerName, int userId) throws Exception {
		// update old live date
		updateLiveDateAsBefore(userId);

		// create new live
		Calendar c = Calendar.getInstance();
		Map<String, Object> updateMap = new HashMap<String, Object>();

		updateMap.put("ActivityRequest->SellerName", sellerName);
		updateMap.put("ActivityRequest->UserId", userId);
		updateMap.put("ActivityRequest->AppConfirmed", 1);
		updateMap.put("ActivityRequest->ActivityName", "自动化_即将开始直播");

		c.add(Calendar.DAY_OF_MONTH, 6);
		updateMap.put("ActivityRequest->StartTime", liveSDF.format(c.getTime()));
		c.add(Calendar.HOUR, 2);
		updateMap.put("ActivityRequest->EndTime", liveSDF.format(c.getTime()));

		return createLive(JsonBeanFile.CreateLiveTpl, updateMap);

	}

	 //创建即将开始的直播
	/***
	 * 
	 * @param sellerName
	 * @param userId
	 * @param LiveType 精品直播为1， 普通直播为0
	 * @return
	 * @throws Exception 
	 */
	public static JSONObject createLiveBeginInFuture(String sellerName, int userId,int LiveType) throws Exception{
		if (LiveType==1){
			return createLiveBeginInFuture(sellerName,userId,JsonBeanFile.CreateLiveJP);
			
		}else{
			return createLiveBeginInFuture(sellerName,userId);
		}
	} 
	
	
	
	
	/***
	 * 创建即将开始的直播
	 * 
	 * @param sellerName
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLiveBeginInFuture(String sellerName, int userId) throws Exception {
		// update old live date
		updateLiveDateAsBefore(userId);

		// create new live
		Calendar c = Calendar.getInstance();
		Map<String, Object> updateMap = new HashMap<String, Object>();

		updateMap.put("ActivityRequest->SellerName", sellerName);
		updateMap.put("ActivityRequest->UserId", userId);
		updateMap.put("ActivityRequest->AppConfirmed", 1);
		updateMap.put("ActivityRequest->ActivityName", "自动化_即将开始直播");
		
		updateMap.put("ActivityRequest->LiveType", 0);
		c.add(Calendar.DAY_OF_MONTH, 1);
		updateMap.put("ActivityRequest->StartTime", liveSDF.format(c.getTime()));
		c.add(Calendar.HOUR, 2);
		updateMap.put("ActivityRequest->EndTime", liveSDF.format(c.getTime()));

		return createLive(JsonBeanFile.CreateLiveTpl, updateMap);

	}

	/***
	 * 创建即将开始的直播
	 * 
	 * @param sellerName
	 * @param userId
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLiveBeginInFuture(String sellerName, int userId, String fileName) throws Exception {
		// update old live date
		updateLiveDateAsBefore(userId);

		// create new live
		Calendar c = Calendar.getInstance();
		Map<String, Object> updateMap = new HashMap<String, Object>();

		updateMap.put("ActivityRequest->SellerName", sellerName);
		updateMap.put("ActivityRequest->UserId", userId);
		updateMap.put("ActivityRequest->AppConfirmed", 1);
		updateMap.put("ActivityRequest->ActivityName", "自动化_即将开始直播");

		c.add(Calendar.DAY_OF_MONTH, 1);
		updateMap.put("ActivityRequest->StartTime", liveSDF.format(c.getTime()));
		c.add(Calendar.HOUR, 2);
		updateMap.put("ActivityRequest->EndTime", liveSDF.format(c.getTime()));

		return createLive(fileName, updateMap);

	}

	/***
	 * 创建未生效的直播
	 * 
	 * @param sellerName
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLiveNotInEffect(String sellerName, int userId) throws Exception {
		// update old live date
		updateLiveDateAsBefore(userId);

		// create new live
		Calendar c = Calendar.getInstance();
		Map<String, Object> updateMap = new HashMap<String, Object>();

		updateMap.put("ActivityRequest->SellerName", sellerName);
		updateMap.put("ActivityRequest->UserId", userId);
		updateMap.put("ActivityRequest->AppConfirmed", 0);
		updateMap.put("ActivityRequest->ActivityName", "自动化_未生效直播");
		updateMap.put("ActivityRequest->Position", null);

		c.add(Calendar.DAY_OF_MONTH, 2);
		updateMap.put("ActivityRequest->StartTime", liveSDF.format(c.getTime()));
		c.add(Calendar.HOUR, 2);
		updateMap.put("ActivityRequest->EndTime", liveSDF.format(c.getTime()));

		return createLive(JsonBeanFile.CreateLiveTpl, updateMap);

	}

	
	public static JSONObject createLiveInProgress(String sellerName, int userId,int LiveType) throws Exception{
		if (LiveType == 1){
			return createLiveInProgress(sellerName,userId,JsonBeanFile.CreateLiveJP);
		}else{
			return createLiveInProgress(sellerName,userId);
		}
	}
			
	/***
	 * 创建正在进行中的直播
	 * 
	 * @param sellerName
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLiveInProgress(String sellerName, int userId, String fileName) throws Exception {

		// create live
		JSONObject liveBean = createLiveBeginInFuture(sellerName, userId, fileName);

		// update live to in progress
		int activityId = liveBean.getJSONObject("Data").getInt("ActivityId");

		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR, -2);
		Date dateStart = liveSDF.parse(liveSDF.format(c.getTime()));
		c.add(Calendar.HOUR, 4);
		Date dateEnd = liveSDF.parse(liveSDF.format(c.getTime()));
		
		updateLiveTime(userId,activityId,dateStart,dateEnd);
		return liveBean;
	}

	
	private static void updateLiveTime(int userId,int liveId, Date dateStart,Date dateEnd) throws Exception{
		// update Sql
		Map<String, Object> updateSQL = MapUtil.hashMap("dBeginTime", dateStart, "dEndTime", dateEnd, "iSellerId",
				userId, "iActivityId", liveId);
		new YmtLiveWapper().updateTimeBySellerIdAndLiveId(updateSQL);

		// updateMongo
		if (YmtMongoDriverFactroy.isOldMongoCheck()) {
			new LiveBasicInfoWapper().update(MapUtil.hashMap("SellerId", userId, "ActivityId", liveId),
					MapUtil.hashMap("StartTime", dateStart, "EndTime", dateEnd));
		}

		if (YmtMongoDriverFactroy.isNewMongoCheck()) {
			new LiveModelWapper().update(MapUtil.hashMap("SellerId", userId, "ActivityId", liveId),
					MapUtil.hashMap("StartTime", dateStart, "EndTime", dateEnd));
		}
		
		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			new LivesWapper().update(MapUtil.hashMap("sid", userId, "lid", liveId),
					MapUtil.hashMap("start", dateStart, "end", dateEnd));
		}
	}
	
	
	/***
	 * 创建正在进行中的直播
	 * 
	 * @param sellerName
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLiveInProgress(String sellerName, int userId) throws Exception {

		// create live
		JSONObject liveBean = createLiveBeginInFuture(sellerName, userId);
		
		// update live to in progress
		int activityId = liveBean.getJSONObject("Data").getInt("ActivityId");

		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR, -2);
		Date dateStart = liveSDF.parse(liveSDF.format(c.getTime()));
		c.add(Calendar.HOUR, 48);
		Date dateEnd = liveSDF.parse(liveSDF.format(c.getTime()));

		updateLiveTime(userId,activityId,dateStart,dateEnd);
		
		new YmtLiveWapper().updateComfirmByLiveId(activityId);
		new LivesWapper().update(MapUtil.hashMap("lid", activityId),
				MapUtil.hashMap("confirm", true));
		
		 Map<String,Object> updateMap = new HashMap<String,Object>();
		 updateMap.put("SellerId", userId);
		 updateMap.put("ActivityId", activityId);
		 updateMap.put("Position", "test");
		 updateMap.put("Latlng", "123,123"); 
		
		  new ConfirmActivityCall().callAndGetReturnData(updateMap);
		
		return liveBean;
	}

	/***
	 * 创建直播
	 * 
	 * @param fileName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject createLive(String fileName, Map<String, Object> updateMap) {
		// create live
		JSONObject createLiveBean = JsonBeanHelper.getJsonBean(fileName);
		JsonBeanHelper.updateJsonBean(createLiveBean, updateMap);
		// 检查返回码
		return new CreateLiveCall().callAndGetReturnData(createLiveBean);

	}

	/**
	 * 结束直播
	 * 
	 * @param activityId
	 *            直播id
	 * @param userId
	 *            用户id
	 * @return 返回报文
	 * @throws Exception
	 */
	public static JSONObject closeLive(int activityId, int sellerId) throws Exception {
		// close live
		CloseActivityCall closeActivityCall = new CloseActivityCall();
		Map<String, Object> calldate = new HashMap<String, Object>();
		calldate.put("ActivityId", activityId);
		calldate.put("UserId", sellerId);
		JSONObject result = closeActivityCall.callAndGetReturnData(calldate);

		return result;
	}

	/***
	 * 修改10天内的直播 为过去时
	 * 
	 * @param sellerId
	 * @return
	 */
	public static void updateLiveDateAsBefore(int sellerId) {
		try {

			Logger.comment("修改现有直播都为过去时间");

			// updateSQL.put("dBeginTime",liveSDF.parse("2016-08-01 22:06:00"));
			// updateSQL.put("dEndTime",liveSDF.parse("2016-08-01 23:16:00"));

			Date dateStart = liveSDF.parse(YMTDateUtil.getBeforeOrNextDay(-20));
			Date dateEnd = liveSDF.parse(YMTDateUtil.getBeforeOrNextDay(-19));

			// update SQL
			Map<String, Object> updateSQL = MapUtil.hashMap("dBeginTime", dateStart, "dEndTime", dateEnd, "iSellerId",
					sellerId);
			ymtLiveWapper.updateTimeBySellerId(updateSQL);

			// Update Mongo
			if (YmtMongoDriverFactroy.isOldMongoCheck()) {
				new LiveBasicInfoWapper().update(MapUtil.hashMap("SellerId", sellerId),
						MapUtil.hashMap("StartTime", dateStart, "EndTime", dateEnd));
			}

			if (YmtMongoDriverFactroy.isNewMongoCheck()) {
				new LiveModelWapper().update(MapUtil.hashMap("SellerId", sellerId),
						MapUtil.hashMap("StartTime", dateStart, "EndTime", dateEnd));
			}
			//增加新java修改过期时间
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) { 
				LivesWapper livesWapper=new LivesWapper();
				ArrayList<Map> livesLst=livesWapper.getLivesBySellId(sellerId);
				for(int i=0;i<livesLst.size();i++)
				{
					JSONObject jo = new JSONObject(livesLst.get(i));
					new LivesWapper().update(MapUtil.hashMap("lid", jo.getInt("lid")),
							MapUtil.hashMap("start", dateStart, "end", dateEnd));
				}
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	/***
	 * 修改直播为过去时间， 返回在startDate和EndDate之间的直播
	 * 
	 * @param sellerId
	 * @param startDate
	 * @param endDate
	 */
	public static void updateLiveDateAsBefore(int sellerId, Date startDate, Date endDate) {
		try {

			Logger.comment("修改现有直播都为过去时间  修改直播时间范围：" + YMTDateUtil.getFormatDateString(startDate) + " -- "
					+ YMTDateUtil.getFormatDateString(endDate));

			// select live during the time
			// 扩大1分钟范围
			startDate = new Date(startDate.getTime() - 60 * 1000);
			endDate = new Date(endDate.getTime() + 60 * 1000);
			List<YmtLive> YmtLiveList = ymtLiveWapper.selectBySellerIdAndInDuringTime(sellerId, startDate, endDate);

			// YmtLiveList.forEach(ymtLive->Logger.debug("修改直播id:"+ymtLive.getIactivityid()));

			Date updateStartDate = liveSDF.parse(YMTDateUtil.getBeforeOrNextDay(-20));
			Date updateEndDate = liveSDF.parse(YMTDateUtil.getBeforeOrNextDay(-19));

			// update SQL

			for (YmtLive ymtLive : YmtLiveList) {
				Map<String, Object> updateSQL = MapUtil.hashMap("dBeginTime", updateStartDate, "dEndTime",
						updateEndDate, "iSellerId", sellerId, "iActivityId", ymtLive.getIactivityid());
				ymtLiveWapper.updateTimeBySellerIdAndLiveId(updateSQL);

				// Update Mongo
				if (YmtMongoDriverFactroy.isOldMongoCheck()) {
					liveBasicInfoWapper.update(
							MapUtil.hashMap("SellerId", sellerId, "ActivityId", ymtLive.getIactivityid()),
							MapUtil.hashMap("StartTime", updateStartDate, "EndTime", updateEndDate));
				}

				if (YmtMongoDriverFactroy.isNewMongoCheck()) {
					liveModelWapper.update(
							MapUtil.hashMap("SellerId", sellerId, "ActivityId", ymtLive.getIactivityid()),
							MapUtil.hashMap("StartTime", updateStartDate, "EndTime", updateEndDate));
				}
			}

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	/***
	 * Live Model 校验
	 * 
	 * @param liveRqBean
	 *            ： liveRqBean =
	 *            LiveCallService.createLiveInProgress(sellerName,
	 *            Integer.valueOf(sellerId));
	 * @param productRqBean
	 *            ：productRqBean = new
	 *            AddLiveProductCall().callAndGetReturnData(MapUtil.hashMap("LoginId",
	 *            sellerName, "UserId", sellerId, "Product->ActivityId",
	 *            liveId));
	 * @param productRqBean
	 *            ：productBean =
	 *            SellerProductCallService.addNewProductNotOnSale(sellerId,sellerName,null);
	 * @param liveId
	 *            ： 153667
	 * @throws Exception
	 */
	public static void checkNewMongoLiveModel(JSONObject liveRqBean, JSONObject productRqBean, int liveId)
			throws Exception {

		JSONObject bean = liveRqBean.getJSONObject("JsonBeanRequest").getJSONObject("ActivityRequest");

		Map<String, Object> mongoData = new LiveModelWapper().getActivityId(liveId);

		Map<String, String> tgtAndActKeyPaths = new HashMap<String, String>();

		tgtAndActKeyPaths.put("ActivityName", "ActivityName");
		tgtAndActKeyPaths.put("Position", "ShopAddress");
		tgtAndActKeyPaths.put("Title", "Title");
		tgtAndActKeyPaths.put("VideoCover", "VideoCover");
		tgtAndActKeyPaths.put("VideoUrl", "VideoUrl");
		tgtAndActKeyPaths.put("UserId", "SellerId");
		tgtAndActKeyPaths.put("PicUrl", "ActivityPicture");
		tgtAndActKeyPaths.put("SellerName", "Seller");

		AssertService.assertResultEqual(tgtAndActKeyPaths, bean, mongoData);

		// check categroylist and brands
		Map<String, Object> tgtMap = new HashMap<String, Object>();
		if (productRqBean == null) {
			// todo 已知问题未修
			// tgtMap.put("CategoryList", null);
			tgtMap.put("Brands", null);
			AssertService.assertResultEqual(tgtMap, mongoData);
		} else {

			JSONObject productBean = productRqBean.getJSONObject("JsonBeanRequest").getJSONObject("Product");
			JSONObject mongoDataMap = new JSONObject(mongoData);
			String brandName = new YmtProductBrandWapper().getProductBrandByBrandId(productBean.getInt("iBrandId"))
					.get(0).get("sBrandEn").toString();

			YmtProductCategoryWapper ymtProductCategoryWapper = new YmtProductCategoryWapper();
			int ThirdCategoryId = Integer.parseInt(productBean.get("iThirdCategoryId").toString());
			Map<String, Object> ret = ymtProductCategoryWapper.getProductCategoryByCategoryId(ThirdCategoryId).get(0);
			String ThirdCategoryName = ret.get("sCategory").toString();

			Logger.verifyEquals(true, mongoDataMap.get("Brands").toString().contains(brandName), "LiveModel-Brand");
			Logger.verifyEquals(true,
					mongoDataMap.get("CategoryList").toString().contains(String.valueOf(ThirdCategoryId)),
					"LiveModel-CategoryId");
			Logger.verifyEquals(true, mongoDataMap.get("CategoryList").toString().contains(ThirdCategoryName),
					"LiveModel-CategoryName");
		}

		// check country
		List<AppCountry> AppCountryList = new AppCountryWapper().selectByCountryId(bean.getInt("CountryId"));
		Logger.verifyEquals(1, AppCountryList.size(), "AppCountryList-count");
		Logger.verifyEquals(AppCountryList.get(0).getScountrynamezh(), mongoData.get("Country").toString(),
				"LiveModel-country");
		Logger.verifyEquals(AppCountryList.get(0).getSflag(), mongoData.get("Flag").toString(), "LiveModel-Flag");

		// check AppConfirm
		boolean tgtConfirm = bean.getInt("AppConfirmed") == 1 ? true : false;
		Logger.verifyEquals(tgtConfirm, Boolean.parseBoolean(mongoData.get("AppConfirmed").toString()),
				"LiveModel-AppConfirmed");

		// check other value
		Logger.verifyEquals(1, Integer.parseInt(mongoData.get("Action").toString()), "LiveModel-Action");
		Logger.verifyEquals(liveId, Integer.parseInt(mongoData.get("ActivityId").toString()), "LiveModel-liveId");

		// check time
		AssertService.assertTime(YMTDateUtil.getDate(), (Date) mongoData.get("AddTime"), 1000);

		if (YMTDateUtil.getDate().getTime() > ((Date) mongoData.get("StartTime")).getTime()) {
			// 表明正在进行直播
			Calendar c = Calendar.getInstance();
			c.add(Calendar.HOUR, -2);
			AssertService.assertTime(c.getTime(), (Date) mongoData.get("StartTime"), 1000);
			c.add(Calendar.HOUR, 4);
			AssertService.assertTime(c.getTime(), (Date) mongoData.get("EndTime"), 1000);

		} else {
			AssertService.assertTime(YMTDateUtil.parseYMDHMSDate(bean.getString("StartTime")),
					(Date) mongoData.get("StartTime"), 1000);
			AssertService.assertTime(YMTDateUtil.parseYMDHMSDate(bean.getString("EndTime")),
					(Date) mongoData.get("EndTime"), 1000);
		}

	}

	/***
	 * 创建直播，一场进行中，多场即将开始 @param sellerName @param userId @param
	 * liveInFutureCount @param duringDay 间隔时间 @return @throws Exception @throws
	 */
	public static List<Integer> createLivesInProcessAndInFuture(int sellerId, String sellerName, int liveInFutureCount,
			int duringDay) throws Exception {
		List<Integer> liveIdList = new ArrayList<Integer>();
		int liveInProcessId = createLiveInProgress(sellerName, sellerId).getJSONObject("Data").getInt("ActivityId");
		liveIdList.add(liveInProcessId);

		for (int i = 0; i < liveInFutureCount; i++) {
			// create new live
			Calendar c = Calendar.getInstance();
			Map<String, Object> updateMap = new HashMap<String, Object>();

			updateMap.put("ActivityRequest->SellerName", sellerName);
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->AppConfirmed", 1);
			updateMap.put("ActivityRequest->ActivityName", "自动化_即将开始直播_" + (i + 1));

			c.add(Calendar.DAY_OF_MONTH, (1 + duringDay * (i + 1)));
			updateMap.put("ActivityRequest->StartTime", liveSDF.format(c.getTime()));
			c.add(Calendar.HOUR, 2);
			updateMap.put("ActivityRequest->EndTime", liveSDF.format(c.getTime()));

			int liveId = createLive(JsonBeanFile.CreateLiveTpl, updateMap).getJSONObject("Data").getInt("ActivityId");
			liveIdList.add(liveId);

		}

		return liveIdList;

	}

	/***
	 * 创建直播，多场即将开始 @param sellerName @param userId @param
	 * liveInFutureCount @param duringDay 间隔时间 @return @throws Exception @throws
	 */
	public static List<Integer> createLivesInFuture(int sellerId, String sellerName, int liveInFutureCount,
			int duringDay) throws Exception {
		updateLiveDateAsBefore(sellerId);
		List<Integer> liveIdList = new ArrayList<Integer>();
		for (int i = 0; i < liveInFutureCount; i++) {
			// create new live
			Calendar c = Calendar.getInstance();
			Map<String, Object> updateMap = new HashMap<String, Object>();

			updateMap.put("ActivityRequest->SellerName", sellerName);
			updateMap.put("ActivityRequest->UserId", sellerId);
			updateMap.put("ActivityRequest->AppConfirmed", 1);
			updateMap.put("ActivityRequest->ActivityName", "自动化_即将开始直播_" + (i + 1));

			c.add(Calendar.DAY_OF_MONTH, (duringDay * (i + 1)));
			updateMap.put("ActivityRequest->StartTime", liveSDF.format(c.getTime()));
			c.add(Calendar.HOUR, 2);
			updateMap.put("ActivityRequest->EndTime", liveSDF.format(c.getTime()));

			int liveId = createLive(JsonBeanFile.CreateLiveTpl, updateMap).getJSONObject("Data").getInt("ActivityId");
			liveIdList.add(liveId);
		}

		return liveIdList;
	}

	public static List<Integer> sortByLiveStartTime(List<Integer> liveidsList) throws Exception {
		Map<Integer, Long> livetimeMap = new HashMap<Integer, Long>();

		// 获取直播开始时间
		for (int i = 0; i < liveidsList.size(); i++) {
			int liveId = liveidsList.get(i);
			YmtLive ymtLive = ymtLiveWapper.selectByLiveId(liveId);
			livetimeMap.put(liveId, ymtLive.getDbegintime().getTime());
		}

		Map<Integer, Long> sortRet = MapUtil.sortByValue(livetimeMap);
		List<Integer> retSortLiveId = new ArrayList<Integer>();
		for (Integer liveId : sortRet.keySet()) {
			retSortLiveId.add(liveId);
		}

		return retSortLiveId;

	}
     public static void CreateLivesProductByLivesId(int sellerId, String sellerName,int ActivityId) throws Exception
     {
    	 //1  创建直播 调用createLivesInProcessAndInFuture、createLiveBeginInFuture、createLiveNotInEffect
    	 List<String> productIds = new ArrayList<>();
 		//2 add new product
 		for (int i=0;i<1;i++){
 		 JSONObject productBean = SellerProductCallService.addNewProductNotOnSale(sellerId,sellerName,null);
 		 String productId =	productBean.getJSONObject("Data").getString("ProductID");
 		 productIds.add(productId);
 		}

 		//3 add product to live
     	JSONObject addProductInLiveBean = SellerProductCallService.addProductsInLive(sellerId,ActivityId,productIds);
 		Logger.verifyEquals( 200,addProductInLiveBean.getInt("Code"), "响应报文-返回码");

     }
     /**根据直播Id，创建指定的商品数量
      * 
      * @param sellerId
      * @param sellerName
      * @param ActivityId
      * @param productNum
      * @throws Exception
      */
     public static void CreateLivesProductByLivesId(int sellerId, String sellerName,int ActivityId,int productNum) throws Exception
     {
    	 //1  创建直播 调用createLivesInProcessAndInFuture、createLiveBeginInFuture、createLiveNotInEffect
    	 List<String> productIds = new ArrayList<>();
 		//2 add new product
 		for (int i=0;i<productNum;i++){
 		 JSONObject productBean = SellerProductCallService.addNewProductNotOnSale(sellerId,sellerName,null);
 		 String productId =	productBean.getJSONObject("Data").getString("ProductID");
 		 productIds.add(productId);
 		}

 		//3 add product to live
     	JSONObject addProductInLiveBean = SellerProductCallService.addProductsInLive(sellerId,ActivityId,productIds);
 		Logger.verifyEquals( 200,addProductInLiveBean.getInt("Code"), "响应报文-返回码");

     }
    
	public static void main(String[] args) throws Exception {
		List<Integer> a  = new ArrayList<>();
		a.add(2);
		a.add(5);
		a.add(56);
		a.add(324);
		a.add(4523);
		
		List<Integer> b= a.subList(1, 5);
		System.out.println(b);
		System.out.println(a.size());

	}

}
